/*
 * 找出每个DAE模型的左上角和右下角的相对坐标，结合中心点坐标，计算出
 * 左上角和右下角的经纬度坐标，输出为JSON备用
 */
var fs = require('fs'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();

function getVertex(inputFileDir, outputFile, centerPointLngLat) {
    // var centerPointXY = latLng2WebMercator(centerPointLngLat[0], centerPointLngLat[1]);
    // for threebox
    var centerPointXY = projectToWorld(centerPointLngLat[0], centerPointLngLat[1]);
    var blockLngLat = {};
    var flag = 0;
    fs.readdirSync(inputFileDir).filter(function(f) {
        return f.endsWith('H.dae');
    }).forEach(function(f) {
        flag++;
        fs.readFile(inputFileDir + '/' + f, function(err, data) {
            parser.parseString(data, function (err, result) {
                var positionsStr = '';
                var geometryArr = result.COLLADA.library_geometries[0].geometry;
                for(var i = 0; i < geometryArr.length; i++) {
                    if (!geometryArr[i].$.id.startsWith('geom-BUILDING') && !geometryArr[i].$.id.startsWith('geom-3D')) {
                        positionsStr = positionsStr.concat(' ', geometryArr[i].mesh[0].source[0].float_array[0]._);
                    }
                };

                positionsStr = positionsStr.trim();
                positionsArr = positionsStr.split(' ');
                var minX = Number(positionsArr[0]),
                    maxX = Number(positionsArr[0]),
                    minY = Number(positionsArr[1]),
                    maxY = Number(positionsArr[1]);
                for(var i = 0; i < positionsArr.length - 2; i += 3) {
                    if(Number(positionsArr[i]) < minX) {
                        minX = Number(positionsArr[i]);
                    }
                    if(Number(positionsArr[i]) > maxX) {
                        maxX = Number(positionsArr[i]);
                    }
                    if(Number(positionsArr[i + 1]) < minY) {
                        minY = Number(positionsArr[i + 1]);
                    }
                    if(Number(positionsArr[i + 1]) > maxY) {
                        maxY = Number(positionsArr[i + 1]);
                    }
                };
                // console.log(f, minX, maxY, maxX, minY);
                // var ltLngLat = webMercator2LngLat((centerPointXY[0] + minX), (centerPointXY[1] + maxY));
                // var rbLngLat = webMercator2LngLat((centerPointXY[0] + maxX), (centerPointXY[1] + minY));

                // for threebox
                var ltLngLat = unprojectFromWorld(minX, maxY, centerPointXY[0], centerPointXY[1], centerPointLngLat[1]);
                var rbLngLat = unprojectFromWorld(maxX, minY, centerPointXY[0], centerPointXY[1], centerPointLngLat[1]);
                // console.log(f, ltLngLat[0], ltLngLat[1], rbLngLat[0], rbLngLat[1]);
                blockLngLat[f] = {};
                blockLngLat[f].ltLng = ltLngLat[0];
                blockLngLat[f].ltLat = ltLngLat[1];
                blockLngLat[f].rbLng = rbLngLat[0];
                blockLngLat[f].rbLat = rbLngLat[1];
                console.log(f, ' accomplished');
                if(!(--flag)) {
                    fs.writeFileSync(outputFile, JSON.stringify(blockLngLat));
                }
            });
        });
    });

    // 经纬度转墨卡托
    function latLng2WebMercator(lng, lat) {
        var x = lng * 20037508.34 / 180;
        var y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
        y = y * 20037508.34 / 180;
        return [x, y];
    }

    // 墨卡托转经纬度
    function webMercator2LngLat(x, y) {
        var lng = x / 20037508.34 * 180;
        var lat = y / 20037508.34 * 180;
        lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);
        return [lng, lat];
    }

    // for threebox
    function unprojectFromWorld(x, y, centerX, centerY, latitude) {
        var pixelsPerMeter = Math.abs(512 * (1 / Math.cos(latitude * Math.PI / 180)) / 40075000);
        x = -x * pixelsPerMeter + centerX;
        y = -y * pixelsPerMeter + centerY;
        var unprojected = [
            -x / ((6378137.0) * (Math.PI / 180) * (512 / (6378137.0 * Math.PI) / 2)),
            2 * (Math.atan(Math.exp(y / ((512 / (6378137.0 * Math.PI) / 2) * (-(6378137.0))))) - Math.PI / 4) / (Math.PI / 180)
        ];
        return unprojected;
    }

    function projectToWorld(lng, lat) {
        // Spherical mercator forward projection, re-scaling to WORLD_SIZE
        var projected = [
            -(6378137.0) * lng * (Math.PI / 180) * (512 / (6378137.0 * Math.PI) / 2),
            -(6378137.0) * Math.log(Math.tan((Math.PI * 0.25) + (0.5 * lat * (Math.PI / 180)))) * (512 / (6378137.0 * Math.PI) / 2)
        ];
        return projected;
    }
}

module.exports = getVertex;